package com.sixmac.police.controller;

import com.sixmac.common.base.BaseController;
import com.sixmac.common.model.system.LoginLog;
import com.sixmac.core.annotation.Before;
import com.sixmac.core.annotation.Json;
import com.sixmac.core.config.Configue;
import com.sixmac.core.constant.Const;
import com.sixmac.core.constant.Constant;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.shiro.ShiroKit;
import com.sixmac.core.toolbox.Func;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.CookieKit;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.core.toolbox.kit.LogKit;
import com.sixmac.core.toolbox.log.BladeLogManager;
import com.sixmac.module.AdminRole;
import com.sixmac.module.AdminUrole;
import com.sixmac.module.AdminUser;
import com.sixmac.module.Room;
import com.sixmac.police.service.AdminUserService;
import com.sixmac.system.meta.intercept.LoginValidator;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminLoginController extends BaseController implements Const {

    @Autowired
    AdminUserService adminUserService;

    @RequestMapping("/")
    public String index(HttpServletRequest request,ModelMap mm) {
        AdminUser user = (AdminUser) request.getSession().getAttribute(Constant.SESSION_ADMIN_USER);
        if(user == null){
            return redirect(Configue.getBaseDomain() + "/server/admin/login");
        }
        mm.put("user",user);
        mm.put("admin",0);
        if (user.getpId()==0&&user.getRoleId()==0){
            mm.put("admin",1);
        }
        return "/police/model.html";
    }

    @RequestMapping("/go")
    public String go(HttpServletRequest request,ModelMap mm) {
        return "/police/default.html";
    }

    /**
     * 登陆地址
     */
    @GetMapping("/login")
    public String login(HttpServletRequest request,ModelMap mm) {
        AdminUser user = (AdminUser) request.getSession().getAttribute(Constant.SESSION_ADMIN_USER);
        if(user != null){
            mm.put("user",user);
            mm.put("admin",0);
            if (user.getpId()==0&&user.getRoleId()==0){
                mm.put("admin",1);
            }
            return "/police/model.html";
        }
        return "/police/login.html";
    }

    @RequestMapping("/login/check")
    @ResponseBody
    public AjaxResult loginCheck(String mobile, String password, Boolean save,String code, HttpServletRequest request, HttpServletResponse response, ModelMap mm) {
        return adminUserService.login(mobile, password, save, request, response);
    }

    /**
     * 登陆地址
     */
    @GetMapping("/model")
    public String model(HttpServletRequest request,ModelMap mm) {
        AdminUser user = (AdminUser) request.getSession().getAttribute(Constant.SESSION_ADMIN_USER);
        if(user == null){
            return "/police/login.html";
        }
        mm.put("user",user);
        AdminRole adminRole = Blade.create(AdminRole.class).findById(user.getRoleId());
        List<AdminUrole> adminUroles = Blade.create(AdminUrole.class).findBy(" roleId = "+user.getRoleId(),null);
        HashMap<Integer,Integer> kes = new HashMap<>();
        for (AdminUrole adminUrole:adminUroles){
            kes.put(adminUrole.getMenuId(),adminUrole.getMenuId());
        }
        mm.put("admin",0);
        if (user.getpId()==0&&user.getRoleId()==0){
            mm.put("admin",1);
        }
        mm.put("menus",kes);

        List<Room> rooms = Blade.create(Room.class).findBy(" region="+user.getAreaId(),null);
        mm.put("rooms",JsonKit.toJson(rooms));
        return "/police/model.html";
    }

    /**
     * 登陆请求
     */
    @Json
    @Before(LoginValidator.class)
    @PostMapping("/login")
    public AjaxResult login(HttpServletRequest request, HttpServletResponse response) {
        String account = getParameter("account");
        String password = getParameter("password");
        String imgCode = getParameter("imgCode");
        if (!validateCaptcha(response, imgCode)) {
            return error("验证码错误");
        }
        return adminUserService.login(account,password,true,request,response);
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().removeAttribute(Constant.SESSION_ADMIN_USER);
        CookieKit.removeCookie(request, response);
        return redirect("/admin/login");
    }

    @RequestMapping("/unauth")
    public String unauth() {
        if (ShiroKit.notAuthenticated()) {
            return redirect("/login");
        }
        return NOPERMISSION_PATH;
    }

    @RequestMapping("/captcha")
    public void captcha(HttpServletResponse response) {
        makeCaptcha(response);
    }

    public void doLog(Session session, String type){
        if(!BladeLogManager.isDoLog()){
            return;
        }
        try{
            LoginLog log = new LoginLog();
            String msg = Func.format("[sessionID]: {} [sessionHost]: {} [sessionHost]: {}", session.getId(), session.getHost(), session.getTimeout());
            log.setLogname(type);
            log.setMethod(msg);
            log.setCreatetime(new Date());
            log.setSucceed("1");
            log.setUserid(Func.toStr(ShiroKit.getUser().getId()));
            Blade.create(LoginLog.class).save(log);
        }catch(Exception ex){
            LogKit.logNothing(ex);
        }
    }

}

